<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="C" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8">
    <title>购物车</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../css/layui.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../css/shop/public.css"/>
    <link rel="stylesheet" type="text/css" href="../css/shop/shouye.css"/>
    <link rel="stylesheet" type="text/css" href="../css/shop/shopcar.css"/>
    <%--    <style type="text/css">--%>
    <%--         .layui-table-cell{--%>
    <%--         height: auto;--%>
    <%--         line-height: 50px;--%>
    <%--         }--%>
    <%--    </style>--%>


</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo layui-hide-xs layui-bg-black">
            <img src="../images/shopping/logo02.png" style="width: 60px;height: 60px">
            BUMA store
        </div>
        <!-- 头部区域 -->
        <ul class="layui-nav layui-layout-left">
            <!-- 移动端显示 -->
            <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
                <i class="layui-icon layui-icon-spread-left"></i>
            </li>
            <li class="layui-nav-item layui-hide-xs"><a href="${pageContext.request.contextPath}/page/shopping/03_merchant.jsp;">我的电商</a></li>
            <li class="layui-nav-item layui-hide-xs"><a href="${pageContext.request.contextPath}/page/shopping/02_personal_center.jsp;">个人中心</a></li>
        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <div class="car">
                    <a href="shopcar.jsp"><img src="../images/shopping/购物车.png" height="28px">
                        <span>购物车</span>
                    </a>
                </div>
            </li>
            <li class="layui-nav-item layui-hide layui-show-sm-inline-block">
                <a href="javascript:;">
                    <img src="//unpkg.com/outeres@0.0.10/img/layui/icon-v2.png" class="layui-nav-img">
                    ${sessionScope.user}
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;">Your Profile</a></dd>
                    <dd><a href="javascript:;">Settings</a></dd>
                    <dd><a href="javascript:;">Sign out</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
                <a href="javascript:;">
                    <i class="layui-icon layui-icon-more-vertical"></i>
                </a>
            </li>
        </ul>
    </div>
</div>

<div class="layui-layout layui-layout-admin" style="margin-top: 80px;">
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 批量删除 </button>
            <button class="layui-btn layui-btn-sm layui-btn-danger " lay-event="count"> 结算 </button>
        </div>
    </script>
    <table class="layui-hide" id="goodsList" lay-filter="currentTableFilter"></table>

</div>

<div id="target-test" style="margin-right: -500px;position: relative; padding: 16px;">
</div>

<!--<script src="//unpkg.com/layui@2.9.16/dist/layui.js"></script>-->
<script src="../js/layui.js"></script>
<script src="../js/jquery-3.6.0.js"></script>
<script>
    layui.use(['form', 'layer'], function () {
        var $ = layui.jquery,
            table = layui.table,
            layer = layui.layer;

        table.render({
            elem: '#goodsList',
            url: 'http://localhost:8080/OnlineShopping/shopping/car/selectGoodsByUsername',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'PImage01', width: 100, title: '图片', sort: true,templet:'#increment',templet: function(d){
                        return '<img src="${pageContext.request.contextPath}/'+d.PImage01 +'"alt="商品图1" style="width: 100px;height: 100px;">';
                    }},
                {field: 'PId', width: 100, title: '商品ID', sort: true},
                {field: 'PName', width: 120, title: '商品名称'},
                {field: 'PType', width: 120, title: '商品类型', sort: true},
                {field: 'PNum', width: 100, title: '数量',sort: true},
                {field: 'PPrice', width: 100,title: '价格',sort: true},
                {field: 'mName', width: 100, title: '店名', sort: true},
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            skin: 'line'
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('goodsList')
                    , data = checkStatus.data;

                if (data.length === 0) {
                    layer.alert('请先选择需要删除的用户',{area: ['380px', '200px'],offset: ['280px', '320px']});
                    return;
                }
                // 提取选中商品PID
                var ids = data.map(function (item) {
                    return item.PId;
                });
                console.log(ids)

                $.get('http://localhost:8080/OnlineShopping/shopping/car/removeGoods', { "ids[]": ids }, function(response) {

                    if (response == 1) {
                        layer.msg('删除成功', { icon: 3 });
                        table.reload('goodsList'); // 重新加载表格
                    } else {
                        layer.msg('删除失败', { icon: 4 });
                    }
                },'json');
            }else if(obj.event === 'count'){
                var checkStatus = table.checkStatus('goodsList')
                    , data = checkStatus.data;

                if (data.length === 0) {
                    layer.alert('请先选择需要结算的商品',{area: ['380px', '200px'],offset: ['280px', '320px']});
                    return;
                }

                // 提取选中商品PID
                var ids = data.map(function (item) {
                    return item.PId;
                });

                var sum = 0
                data.map(function (item) {
                    return sum += item.PPrice * item.PNum;
                });
                console.log(sum)

                // 添加一个订单
                $.get('http://localhost:8080/OnlineShopping/shopping/car/addOrder', { "ids[]": ids }, function(response) {

                    if (response == 1) {
                        layer.msg('成功下单！，共'+sum+'元', { icon: 3 });
                    }
                },'json');

                // 从购物车中删除
                $.get('http://localhost:8080/OnlineShopping/shopping/car/removeGoods', { "ids[]": ids }, function(response) {
                    if (response == 1) {
                        table.reload('goodsList'); // 重新加载表格
                    }
                },'json');
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            console.log('PId: '+data.PId);
            console.log('obj_event:'+obj.event);
            if(obj.event === "detail"){
                var index = layer.open({
                    title: '查看详情',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    offset: ['0px', '0px'],
                    area: ['100%', '100%'],
                    content: '${pageContext.request.contextPath}/ShopServlet?method=findById&PId='+data.PId+'&flag=0',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }else if (obj.event === 'edit') {

                var index = layer.open({
                    title: '编辑商品',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    offset: ['0px', '0px'],
                    content: '${pageContext.request.contextPath}/ShopServlet?method=findById&PId='+data.PId+'&flag=1',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }else if(obj.event === 'img'){
                var index = layer.open({
                    title: '编辑图片',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    offset: ['0px', '0px'],
                    area: ['100%', '100%'],
                    content: '${pageContext.request.contextPath}/page/shopping/merchant/upload.jsp?PName='+data.PName,
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么',{area: ['380px', '200px'],offset: ['280px', '320px']},function (index) {
                    /*请求地址*/
                    $.get('${pageContext.request.contextPath}/ShopServlet?method=removeById',{"PId":data.PId},function (data){
                        if(data==1){
                            layer.msg('删除成功',{icon:1});
                            table.reload('currentTableId', {
                                page: {
                                    curr: 1
                                }
                            });
                        }else{
                            layer.msg('删除失败',{icon:2});
                        }
                    },'json');

                    layer.close(index);
                });
            }
        });

    });
</script>
<script>
    function add(){
        var textBox = document.getElementById('count');
        var currentValue = parseInt(textBox.value);
        var newValue = currentValue + 1;
        textBox.value = newValue.toString();
    }
    function sub(){
        var textBox = document.getElementById('count');
        var currentValue = parseInt(textBox.value);
        if(currentValue == 1){
            alert("商品数量至少为1")
            return
        }
        var newValue = currentValue - 1;
        textBox.value = newValue.toString();
    }
</script>

<script>
    layui.use(function () {
        var util = layui.util;
        // 自定义固定条
        util.fixbar({
            bars: [{ // 定义可显示的 bar 列表信息 -- v2.8.0 新增
                type: 'share',
                icon: 'layui-icon-share'
            }, {
                type: 'help',
                icon: 'layui-icon-help'
            }, {
                type: 'cart',
                icon: 'layui-icon-cart',
                // style: 'background-color: #FF5722;'
            }, {
                type: 'groups',
                content: '群',
                style: 'font-size: 21px;'
            }],
            // bar1: true,
            // bar2: true,
            // default: false, // 是否显示默认的 bar 列表 --  v2.8.0 新增
            // bgcolor: '#393D52', // bar 的默认背景色
            // css: {right: 100, bottom: 100},
            // target: '#target-test', // 插入 fixbar 节点的目标元素选择器
            // duration: 300, // top bar 等动画时长（毫秒）
            on: { // 任意事件 --  v2.8.0 新增
                mouseenter: function (type) {
                    layer.tips(type, this, {
                        tips: 4,
                        fixed: true
                    });
                },
                mouseleave: function (type) {
                    layer.closeAll('tips');
                }
            },
            // 点击事件
            click: function (type) {
                console.log(this, type);
                // layer.msg(type);
            }
        });
    });
</script>
<script type="module">

    //JS
    layui.use(['element', 'layer', 'util'], function () {
        var element = layui.element;
        var layer = layui.layer;
        var util = layui.util;
        var $ = layui.$;

        window.onload = function (){
            selectGoodsByUsername();
        }

        util.on('lay-on', {
            // alert: function () {
            //     layer.alert('成功下单！');
            // },
            confirm: function(){
                layer.confirm('确定结算吗？', {
                    btn: ['确定', '关闭'] //按钮
                }, function(){
                    alert("结算完毕")
                    window.location.href = 'shopping.jsp'
                }, function(){
                });
            },


        });

        async function selectGoodsByUsername() {
            try {
                const response = await fetch('http://localhost:8080/OnlineShopping/shopping/car/selectGoodsByUsername');
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json(); // 解析JSON数据
                this.goodsList=data
                console.log(this.goodsList);
            } catch (error) {
                console.error('There was a problem with your fetch operation:', error);
            }
        }
        // function selectGoodsByUsername() {
        //     axios.get().then()
        //     $.get("/OnlineShopping/shopping/car/selectGoodsByUsername", function (data) {
        //         console.log(data)
        //         this.goodsList=data
        //     })
        // }
    });
</script>

</body>
</html>
